import { expose } from "threads"
import { logger } from './log';

interface IData {
    ID: number;
    data: any[];
    sta: number[];
    battery?: number;
    signal?: number;
}
// 解析各种类型的数据
interface parseKindofData {
    [key: string]: (data: string,offset: number) => [string | number,number];
}

// 自定义多种解析数据
const parseObj: parseKindofData = {
    // 解析时间
    time: (data: string,offset: number) => {
        let time: string = ''
        for(let i = 0; i < 4; i++) {
            time += parseInt(data.substring(offset, offset + 2),16).toString()
            offset += 2
            if(i < 3) time += '-'
        }
        return [time,offset]
    },
    //解析电量
    battery: (data: string,offset: number) => {
        let battery = parseInt(data.substring(offset, offset + 2),16)
        offset += 2
        if (battery > 100) {
            battery = 100
        }
        return [battery,offset]
    },
    // 解析信号强度
    signal: (data: string,offset: number) => {
        let signal = parseInt(data.substring(offset, offset + 2),16)
        offset += 2
        if (signal > 127) {
            signal -= 256
        }
        return [signal,offset]
    },
  
}
  // 捕获错误
const catchError = (data: IData,settingData): IData => {
    let catch_uv = settingData[0][0].current_val // 紫外报警阈值
    let catch_ir = settingData[0][1].current_val // 红外报警阈值
    let catch_temp = settingData[0][2].current_val // 温度报警阈值
    let catch_hum = settingData[0][3].current_val // 湿度报警阈值
    let catch_pre = settingData[0][4].current_val // 压力报警阈值
    let catch_param = [catch_temp, catch_hum,catch_pre, catch_ir, catch_uv]
    let new_sta: number[] = []
    if (data.data.length >=5) {
        let uvc_data: number[] = data.data.slice(4)
        let other_data: number[] = data.data.slice(0,4)
        new_sta = other_data.map((item: any, index: number) => { 
            if (item > catch_param[index]) {  
                return 1
            } else {
                return 0
            }
        });
        new_sta.push(Number(uvc_data.some(item => item > catch_uv)))
    } else {
        new_sta = [0,0,0,0,0]
    }
    return {
        ID: data.ID,
        data: data.data,
        sta: new_sta,
        battery: data.battery,
        signal: data.signal
    }
}

// 解析单个数据包的函数
function parseDataPacket(hexStr: string, settingData: Record<string, any>): any {
    // 去除空格并转大写
    hexStr = hexStr.replace(/\s+/g, '').toUpperCase();

    // 查找帧头和帧尾
    const header = 'F7F7';
    const footer = '7F7F';
    const headerIndex = hexStr.indexOf(header);
    const footerIndex = hexStr.indexOf(footer, headerIndex + 4);

    if (headerIndex === -1 || footerIndex === -1) return null;

    // 截取有效数据段
    const dataStr = hexStr.substring(headerIndex + 4, footerIndex);

    // 依次解析
    const ID = parseInt(dataStr.substring(0, 2), 16);

    // 跳过功能码和数据长度
    let offset = 2 + 2 + 2; // ID(2) + 功能码(2) + 长度(2) = 6

    // 解析这个长度的数据
    const dataLength = parseInt(dataStr.substring(4, 6), 16);

    // 温度
    const temp = (parseInt(dataStr.substring(offset, offset + 4), 16) / 100).toFixed(1);
    offset += 4;
    // 湿度
    const hum = (parseInt(dataStr.substring(offset, offset + 4), 16) / 100).toFixed(1);
    offset += 4;
    // 压力
    const pre = (parseInt(dataStr.substring(offset, offset + 4), 16) / 100).toFixed(1);
    offset += 4;
    // 红外
    const ir = (parseInt(dataStr.substring(offset, offset + 4), 16) / 100).toFixed(1);
    offset += 4;
    // 紫外10组
    const uvList: number[] = [];
    for (let i = 0; i < 10; i++) {
        uvList.push(parseInt(dataStr.substring(offset, offset + 4), 16));
        offset += 4;
    }
    let battery: number = 0; // 电池电量
    let signal: number | undefined // 信号强度
    // 时间
    let time: string = ''
    for(let key in parseObj) {
        if (offset - 6 > dataLength * 2) break
        let [value,newOffset] = parseObj[key](dataStr,offset)
        if(key === 'time') {
            time = value as string
        } else if(key === 'battery') {
            battery = value as number
        } else if(key === 'signal') {
            signal = value as number
        }
        offset = newOffset
    }
    let data = {
        ID,
        data: [Number(temp), Number(hum), Number(pre), Number(ir), ...uvList],
        sta: [0, 0, 0, 0, 0],
        battery: battery ? Number(battery) : undefined,
        time,
        signal: signal ? signal : undefined
    };
    // 安全检查：仅当settingData有效时才执行catchError
    if (settingData && Object.keys(settingData).length > 0) {
        return catchError(data, settingData)
    }
    return data;
}

// 新的主处理函数，处理Buffer数据并返回处理结果
export const processBufferData = (input: { hexData: string, address: string, settingData: Record<string,any> }): any => {
    try {
        // 严格的参数验证
        if (!input || typeof input !== 'object') {
            logger.error('processBufferData: 参数必须是对象');
            return { processedData: [], remainingBuffer: '' };
        }
        
        const { hexData, address, settingData } = input;
        
        if (!hexData || typeof hexData !== 'string') {
            logger.error('processBufferData: hexData 必须是非空字符串');
            return { processedData: [], remainingBuffer: '' };
        }
        
        if (!address || typeof address !== 'string') {
            logger.error('processBufferData: address 必须是非空字符串');
            return { processedData: [], remainingBuffer: '' };
        }
        
        // 验证hexData是否为有效的十六进制字符串
        if (!/^[0-9a-fA-F]*$/.test(hexData)) {
            logger.error('processBufferData: hexData 包含无效的十六进制字符');
            return { processedData: [], remainingBuffer: '' };
        }
        
        const hexStr = hexData;
        const processedData: any[] = [];
        let remainingHex = hexStr;
        let processCount = 0;
        const maxProcessCount = 50; // 防止无限循环
        
        // 添加详细的调试日志
        if (hexStr.length > 200) {
           
        }
        
        // 处理缓冲区中的所有完整数据包 - 回归基于协议长度的可靠解析
        while (remainingHex.length >= 24 && processCount < maxProcessCount) { // 最小包长度：帧头2+ID1+功能码1+长度1+最小数据区+校验2+帧尾2 = 12字节 = 24hex
            const header = 'F7F7';
            const footer = '7F7F';
            const headerIndex = remainingHex.toUpperCase().indexOf(header);
            
            if (headerIndex === -1) {
                // 未找到帧头，清空缓冲区
                if (remainingHex.length > 0) {
                    logger.warn(`数据解析错误 - 未找到帧头 [${address}]: 清空缓冲区数据=${remainingHex}`);
                }
                remainingHex = '';
                break;
            }
            
            if (headerIndex > 0) {
                // 丢弃帧头前的垃圾数据
                const discardedData = remainingHex.substring(0, headerIndex);
                logger.warn(`数据解析错误 - 丢弃垃圾数据 [${address}]: ${discardedData}`);
                remainingHex = remainingHex.substring(headerIndex);
            }
            
            // 头部最小长度：帧头2+ID1+功能码1+长度1=5字节=10 hex
            if (remainingHex.length < 10) break;
            
            // 取出数据长度字段（第5字节，hex第8-9位）
            const dataLenHex = remainingHex.substring(8, 10);
            const dataLen = parseInt(dataLenHex, 16);
            
            // 验证数据长度是否合理
            if (isNaN(dataLen) || dataLen < 0 || dataLen > 1000) {
                logger.error(`数据解析错误 - 数据长度无效 [${address}]: ${dataLen}`);
                remainingHex = remainingHex.substring(4); // 跳过整个帧头
                processCount++;
                continue;
            }
            
            // 包总长度=帧头2+ID1+功能码1+长度1+数据区N+校验2+帧尾2
            const totalLen = 2+1+1+1+dataLen+2+2; // 单位：字节
            const totalHexLen = totalLen * 2; // 单位：hex字符
            
            if (remainingHex.length < totalHexLen) {
                // 数据还不够，等待下次
                break;
            }
            
            // 截取完整包
            const packet = remainingHex.substring(0, totalHexLen);
            
            // 检查数据包内部是否包含其他帧头（除了开头的帧头）
            const innerData = packet.substring(4, packet.length - 4); // 排除开头帧头和结尾帧尾
            const innerHeaderIndex = innerData.toUpperCase().indexOf(header);
            if (innerHeaderIndex !== -1) {
                logger.warn(`数据解析警告 - 数据包内部发现帧头 [${address}]: 位置=${innerHeaderIndex + 4}, 数据包=${packet}`);
                // 截断到内嵌帧头位置，重新处理
                remainingHex = remainingHex.substring(innerHeaderIndex + 4);
                processCount++;
                continue;
            }
            
            // 校验帧尾
            const tail = packet.substring(packet.length - 4).toUpperCase();
            if (tail !== footer) {
                logger.error(`数据解析错误 - 帧尾校验失败 [${address}]: 期望=${footer}, 实际=${tail}, 数据包=${packet}`);
                // 丢弃本帧头，继续找下一个
                remainingHex = remainingHex.substring(4); // 跳过整个帧头而不是2个字符
                processCount++;
                continue;
            }
            
            try {
                // 解析数据包
                const jsonData = parseDataPacket(packet, settingData || {});
                if (jsonData && typeof jsonData === 'object') {
                    processedData.push(jsonData);
                }
            } catch (parseError) {
                logger.error(`数据包解析错误 [${address}]: ${(parseError as Error).message}`);
            }
            
            // 移除已处理的数据包
            remainingHex = remainingHex.substring(totalHexLen);
            processCount++;
        }
        
        if (processCount >= maxProcessCount) {
            logger.warn(`processBufferData: 达到最大处理数量限制 (${maxProcessCount}) [${address}]`);
        }

        // 返回处理结果和剩余缓冲区
        return {
            processedData,
            remainingBuffer: remainingHex
        };
        
    } catch (error) {
        logger.error(`工作线程处理错误: ${(error as Error).message}`, {
            error: (error as Error).stack
        });
        return {
            processedData: [],
            remainingBuffer: ''
        };
    }
};

expose(processBufferData)